import { defineStore } from 'pinia';

import { localStg } from '@/utils';

import { clearAuthStorage, getTokenInfo, getUserInfo } from './helpers';
import { fetchGetUserInfo, fetchLogin, fetchLogout } from '~/src/service/api/auth';

/** 授权状态 */
interface AuthState {
    /** 用户信息 */
    userInfo: Auth.UserInfo | null;
    /** 用户token */
    tokenInfo: Auth.Token | null;
    /** 登录的加载状态 */
    loginLoading: boolean;
}

export const useAuthStore = defineStore('auth-store', {
    state: (): AuthState => ({
        userInfo: getUserInfo(),
        tokenInfo: getTokenInfo(),
        loginLoading: false
    }),
    getters: {
        /** 是否登录 */
        isLogin(state) {
            return state.tokenInfo != null;
        }
    },
    actions: {
        /** 清除验证缓存 */
        resetAuthStore() {
            clearAuthStorage();
            this.$reset();
        },
        /** 更新用户信息 */
        async updateUserInfo() {
            let getUserInfoResult = (await fetchGetUserInfo()) as Api.Result<Auth.UserInfo>;
            let userInfo = getUserInfoResult.data;
            // 成功后把用户信息存储到缓存中
            localStg.set('userInfo', userInfo);
            this.userInfo = userInfo;
        },
        /** 登录成功处理 */
        async loginSuccessHandler(loginResult: Api.Result<Boolean>) {
            if (loginResult.data) {
                await this.updateUserInfo();
                // 更新 token 信息
                let tokenInfo = localStg.get('tokenInfo');
                this.tokenInfo = tokenInfo;
            } else {
                this.resetAuthStore();
            }
        },
        /** 登录处理 */
        async loginHandler(params: User.Login) {
            let loginResult = (await fetchLogin(params)) as Api.Result<Boolean>;
            await this.loginSuccessHandler(loginResult);
            return loginResult;
        },
        /** 登出处理 */
        async logoutHandler() {
            let logoutResult = await fetchLogout();
            if (logoutResult.success) {
                await clearAuthStorage();
                this.tokenInfo = null;
                this.userInfo = null;
                window.$message?.info('登出成功');
            }
        }
    }
});
